#!/usr/local/bin/pythonw
# -*- coding: utf-8 -*-
import re
import sys
import time
from LCS_Ukkonen import LCS
from Boitoutils import *
from rstr_max_test import *
import math

def moyenne_len_rstr(l_rstr) :
  total = 0.
  nb_rstr = len(l_rstr)
  for rstr in l_rstr :
    total += len(rstr)
  return total / nb_rstr

def l_rstr2l_len(l_rstr) :
  res = [len(rstr) for rstr in l_rstr]
  return res

def median_len_rstr(l_rstr) :
  l_len = l_rstr2l_len(l_rstr)
  l_len.sort()
  mid = int(math.ceil(len(l_len)/2))
  return l_len[mid]

def statistique_paragraphe(l_rstr) :
  res = {}
  moyenne = moyenne_len_rstr(l_rstr)
  median = median_len_rstr(l_rstr)
  res['moyenne'] = moyenne
  res['median'] = median
  return res

def analyse(resume, paragraphes):
    relevantcontent = []
    for paragraphe in paragraphes:
	res = test(resume, paragraphe)
        relevantcontent.append(res)
    return relevantcontent


def enregistrer_score(fichier,sortie):
    wfi=open('sortie','a')
    log=fichier
    for elem in sortie:
        log += '\t%s'%(elem)
    print>>wfi,log
    wfi.close()

def tester_paires():
  tableau = './corpus/log_reference_appr.txt'
  ofi = open(tableau,'r')
  lignes = ofi.readlines()
  ofi.close()
  for ligne in lignes:
    ligne = re.sub('\n','',ligne)
    triplet = re.split('\t',ligne)
#    print triplet
    resume = './corpus/res/' + triplet[0]
    art = './corpus/art/' + triplet[1]
    txt = './corpus/txt/' + triplet[2]
    traiter_article(resume, art)
    traiter_article(resume, txt)
        
def traiter_corpus(resume, corpus) :
  for article in corpus:
    print '\r', article,
    traiter_article(resume, article)

def traiter_article(resume, article) :
  chaine1 = LireFichierTexte(resume)
  chaine2 = LireFichierTexte(article)
  patt = re.compile('<p>(.*?)</p>')
  paragraphes = re.findall(patt,chaine2)
  relevantcontent = analyse(chaine1, paragraphes)
  for l in relevantcontent :
    res = statistique_paragraphe(l)
    print res
#        enregistrer_score(fichier,sortie)

        
if __name__ == "__main__":
    debut=time.clock()
    resume = sys.argv[1]
    article = sys.argv[2]
#    corpus=sys.argv[2:]
    wfi=open('sortie','w')
    wfi.close()
#    tester_paires()
#    traiter_corpus(resume, corpus)
    traiter_article(resume, article)
    fin=time.clock()
    print fin-debut
    
    
